<template>
  <div class="ele-body">
    <a-card :bordered="false">
      <vxe-grid ref='supplyMaterialGrid' v-bind="gridOptions" class="my-grid66">
        <!--搜索表单 -->
        <template #form>
          <a-form
            :model="where"
            :label-col="{md: {span: 8}, sm: {span: 24}}"
            :wrapper-col="{md: {span: 16}, sm: {span: 24}}">
            <a-row>
              <a-col :lg="5" :md="12" :sm="24"
                     :xs="24">
                <a-form-item label="供应商名称:" name="supplierName">
                  <m-entity-select
                    v-model:value="where.supplierId"
                    placeholder="通过供应商查询"
                    module="material"
                    entity="Supplier"
                    show-options-name="name"
                    class="ele-fluid"
                  />
                </a-form-item>
              </a-col>

              <a-col :lg="6" :md="12" :sm="24"
                     :xs="24">
                <a-form-item label="材料:" name="name">
                  <m-entity-select
                    v-model:value="where.materialId"
                    placeholder="通过材料查询"
                    module="material"
                    entity="Material"
                    show-options-name="name"
                    class="ele-fluid"
                  />
                </a-form-item>
              </a-col>

              <a-col :lg="13" :md="12" :sm="24" :xs="24">
                <a-form-item class="ele-text-right" :wrapper-col="{span: 24}">
                  <a-space>
                    <a-button type="primary" @click="reload">查询</a-button>
                    <a-button @click="reset">重置</a-button>
                  </a-space>
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </template>

        <template #operate="{ row }">
          <a-space>
            <a class="ele-text-success" @click="addToOrder(row)">加入采购单</a>
<!--            <a-divider type="vertical"/>-->
<!--            <a class="ele-text-warning" @click="viewEvent(row)">查看</a>-->
          </a-space>
        </template>

        <template #ycs>
          <a-space>
            <a-button type="primary" @click="viewOrderList()">
              <template #icon>
              </template>
              <span>查看采购单</span>
            </a-button>
            <a-button @click="gridOptions.sortConfig.multiple=!gridOptions.sortConfig.multiple">
              <template #icon>
                <upload-outlined/>
              </template>
              <span>{{ gridOptions.sortConfig.multiple === false ? '单' : '多' }}字段排序</span>
            </a-button>
          </a-space>
        </template>

        <template #pager>
          <vxe-pager
            v-model:current-page="tablePage.currentPage"
            v-model:page-size="tablePage.pageSize"
            :page-sizes="tablePage.pageSizes"
            :total="tablePage.total"
            @page-change="handlePageChange">
          </vxe-pager>
        </template>
      </vxe-grid>

      <!--编辑弹窗-->
      <vxe-modal v-model="supplyMaterialListApp.editModalShowing" ref="supplyMaterialEditModal"
                 :title="gridOptions.showEditTitle"
                 id="supplyMaterialEditModal"
                 width="800" height="400" min-width="460" min-height="320" :lock-view="false" :mask="false"
                 show-footer show-zoom resize remember storage transfer dblclickZoom
                 :destroy-on-close="true"
      >
        <template #default>
          <div id="supplyMaterialEditModalContent">
          </div>
        </template>
        <template #footer>
          <div id="supplyMaterialEditModalFooter">
          </div>
          <teleport to="#supplyMaterialEditModalContent">
            <supplyMaterial-edit ref="supplyMaterial-edit"/>
          </teleport>
        </template>
      </vxe-modal>

      <!--查看弹窗-->
      <vxe-modal v-model="supplyMaterialListApp.viewModalShowing" :title="gridOptions.showDetailsTitle"
                 id="supplyMaterialViewModal"
                 width="600"
                 min-width="460"
                 min-height="320"
                 :destroy-on-close="true"
                 :lock-view="false" :mask="false"
                 footer
                 show-footer show-zoom resize remember storage transfer dblclickZoom>
        <template #default>
          <supplyMaterial-detail ref="supplyMaterial-detail"/>
        </template>
      </vxe-modal>

      <!--加入到采购单弹窗-->
      <vxe-modal v-model="supplyMaterialListApp.orderModalShowing" :title="gridOptions.OrderDetailsTitle"
                 id="supplyMaterialOrderModal"
                 width="600"
                 min-width="460"
                 min-height="320"
                 :destroy-on-close="true"
                 :lock-view="false" :mask="false"
                 footer
                 show-footer show-zoom resize remember storage transfer dblclickZoom>
        <template #default>
          <div id="supplyMaterialOrderModalContent">
          </div>
        </template>
        <template #footer>
          <div id="supplyMaterialOrderModalFooter">
          </div>
          <teleport to="#supplyMaterialOrderModalContent">
            <SupplyMaterialOrder ref="supplyMaterial-order"/>
          </teleport>
        </template>
      </vxe-modal>

      <!--查看采购单弹窗-->
      <vxe-modal v-model="supplyMaterialListApp.orderListModalShowing" :title="gridOptions.OrderDetailsTitle"
                 id="supplyMaterialOrderListModal"
                 width="600"
                 min-width="460"
                 min-height="320"
                 :destroy-on-close="true"
                 :lock-view="false" :mask="false"
                 footer
                 show-footer show-zoom resize remember storage transfer dblclickZoom>
        <template #default>
          <div id="supplyMaterialOrderListModalContent">
          </div>
        </template>
        <template #footer>
          <div id="supplyMaterialOrderListModalFooter">
          </div>
          <teleport to="#supplyMaterialOrderListModalContent">
            <SupplyMaterialOrderDetail ref="supplyMaterial-ordeDetail" @orderId="updateOrderId($event)" @orderListModalShowing="closeOrderDetail($event)"/>
          </teleport>
        </template>
      </vxe-modal>
    </a-card>
  </div>
</template>

<script>
import {defineComponent, reactive, ref, toRefs, provide, onMounted} from 'vue'
import {VXETable} from 'vxe-table'
import {SupplyMaterialService} from "@/views/restaurant/material/supplyMaterial/supplyMaterialService";
import SupplyMaterialEdit
  from "@/views/restaurant/material/supplyMaterial/supplyMaterial-edit";
import SupplyMaterialDetail
  from "@/views/restaurant/material/supplyMaterial/supplyMaterial-detail";
import SupplyMaterialOrder
  from "@/views/restaurant/material/supplyMaterial/supplyMaterial-order";
import SupplyMaterialOrderDetail
  from "@/views/restaurant/material/supplyMaterial/supplyMaterial-orderDetail";
import MEntitySelect from "@/components/MEntity/entitySelect";
import {useRouter} from "vue-router";


export default defineComponent({
  components: {
    SupplyMaterialEdit,
    SupplyMaterialDetail,
    SupplyMaterialOrder,
    SupplyMaterialOrderDetail,
    MEntitySelect
  },
  setup() {
    const router = useRouter();
    const tablePage = reactive({
      total: 0,
      currentPage: 1,
      pageSize: 10,
      pageSizes: [5, 10, 15, 20, 50]
    })
    let orderId = ref(router.currentRoute.value.query.orderId?router.currentRoute.value.query.orderId:null)
    let cart = reactive(JSON.parse(localStorage.getItem('cart')) || [])
    const supplyMaterialGrid = ref({})// as VxeGridInstance
    // 搜索表单是否展开
    let searchExpand = ref(false)
    let proxyInfo = reactive({})
    const where = ref({})
    const eid = ref({})
    const startIndex = ref({})
    const supplyMaterialListApp = reactive({
      editModalShowing: false,
      viewModalShowing: false,
      orderModalShowing: false,
      orderListModalShowing: false,
      editModalForEdit: false,
      addModalForEdit: false,
      orderModalForEdit: false,
    })
    console.log(router.query)

    onMounted(() => {
      console.log(router.query)
      if (router.query) {
        supplyMaterialListApp.orderListModalShowing = router.query.edit
      }
    });

    const gridOptions = reactive({
      border: true,
      resizable: true,
      showHeaderOverflow: true,
      showOverflow: true,
      highlightHoverRow: true,
      keepSource: true,
      id: 'supplyMaterialsGrid',
      // maxHeight: "100%",//表格高度
      height: 800,
      rowId: 'eid',
      selectRow: null,
      showEdit: false,
      showDetails: false,
      showEditTitle: '新建',
      OrderEditTitle: '加入到采购单',
      OrderDetailsTitle: '查看采购单',
      showDetailsTitle: '查看',
      formData: {},//自定义的
      detailData: [],
      startIndex: startIndex,
      printConfig: {
        columns: [
          {field: 'name'},
          {field: 'email'},
          {field: 'nickname'},
          {field: 'age'},
          {field: 'amount'}
        ]
      },
      /*TODO:排序配置 */
      sortConfig: {
        trigger: 'cell',
        remote: true,
        multiple: true,//多字段排序，默认单排序
        showIcon: true,
        // iconAsc: "fa fa-arrow-up fa-1x",
        // iconDesc: "fa fa-arrow-down fa-1x",
      },
      customConfig: {
        storage: true
      },
      /*TODO:过滤器配置*/
      filterConfig: {
        remote: true
      },
      /*TODO:分页配置*/
      pagerConfig: {
        pageSize: 10,
        pageSizes: [5, 10, 15, 20, 50]
      },
      /*TODO:工具栏配置*/
      toolbarConfig: {
        slots: {buttons: 'ycs'},
        refresh: true,
        import: false,
        export: false,
        print: false,
        zoom: true,
        custom: true
      },
      /*TODO:请求代理配置*/
      proxyConfig: {
        seq: true, // 启用动态序号代理，每一页的序号会根据当前页数变化
        sort: true, // 启用排序代理，当点击排序时会自动触发 query 行为
        filter: true, // 启用筛选代理，当点击筛选时会自动触发 query 行为
        form: false, // 启用表单代理，当点击表单提交按钮时会自动触发 reload 行为
        // 对应响应结果 { result: [], page: { total: 100 } }
        props: {
          result: 'data.datas', // 配置响应结果列表字段
          total: 'data.totalCount', // 配置响应结果总页数字段
          message: 'data.msg'
        },
        /*TODO:请求*/
        ajax: {
          /*TODO:分页条件查询*/
          query: ({page, sorts, filters}) => {  // 接收 Promise

            const conditions = {...where.value}
            // console.log(sorts)
            // 处理筛选条件
            filters.forEach(({property, values}) => {
              conditions[property] = values.join('$|$')
            })
            const queryParams = {}
            if (tablePage) {//自定义的
              queryParams.currentPage = tablePage.currentPage
              queryParams.pageSize = tablePage.pageSize
            } else {//默认配置项
              queryParams.currentPage = page.currentPage
              queryParams.pageSize = page.pageSize
            }
            startIndex.value = (queryParams.currentPage - 1) * queryParams.pageSize + 1
            // // 处理筛选条件
            queryParams.filters = conditions;
            // // 处理排序条件
            // let orderBys = [{
            //   property: "substringIndex(\"'待入库','待提交','打回','待审核','已入库','已退货','已取消'\",t0.status,1)",
            //   order: ""
            // }]
            // queryParams.orderBys = orderBys;
            queryParams.orderBys = sorts;
            //
            const $grid = supplyMaterialGrid.value
            $grid.queryParams = queryParams
            return SupplyMaterialService.findSupplyMaterials(queryParams).then(res => {
              tablePage.total = res.data.totalCount;
              if (tablePage.currentPage > tablePage.total) {
                tablePage.currentPage = 1;
              }
              return res;
            }).catch(error => {
              VXETable.modal.message({content: `加载数据出错，原因是：${error.message}`, status: 'error'});

            })
          },
        }
      },

      /*TODO:数据表列*/
      columns: [
        /*多选checkbox 单选seq*/
        {type: 'seq', title: '#', width: 40},
        {
          field: 'name',
          title: '材料名称',
          sortable: true
        },
        {
          field: 'supplierName',
          title: '供应商名称',
          sortable: true
        },
        {
          field: 'todayPrice',
          title: '价格',
          sortable: true,
          formatter({cellValue}){
            if(cellValue!=null){
              return cellValue.toFixed(2)
            }
          }
        },
        {
          field: 'stock',
          title: '余量',
          sortable: true,
          formatter({cellValue}){
            if(cellValue!=null){
              return cellValue.toFixed(2)
            }
          }
        },
        {
          field: 'failuresNum',
          title: '不合格次数',
          sortable: true
        },

        {title: '操作', width: 250, slots: {default: 'operate'}}
      ],

      /*TODO:复选框配置*/
      checkboxConfig: {
        labelField: 'eid',
        reserve: false,
        highlight: false,
        range: true
      },
      /*TODO:编辑验证*/
      editRules: {
        name: [
          {required: true, message: 'app.body.valid.rName'},
          {min: 3, max: 50, message: '名称长度在 3 到 50 个字符'}
        ],
        email: [
          {required: true, message: '邮件必须填写'}
        ],
        role: [
          {required: true, message: '角色必须填写'}
        ]
      },
      editConfig: {
        trigger: 'click',
        mode: 'row',
        showStatus: true
      }
    })//as VxeGridProps
    provide('supplyMaterialListApp', supplyMaterialListApp)
    provide('gridOptions', gridOptions)

    /*TODO:新建事件*/
    const addEvent = () => {
      supplyMaterialListApp.editModalShowing = true
      supplyMaterialListApp.currentId = null;
      supplyMaterialListApp.addModalForEdit = true;
      gridOptions.showEditTitle = "新建";
    }

    /*TODO:查看采购单*/
    const viewOrderList = () => {
      // router.push(`/restaurant/material/supplyMaterial/supplyMaterial-edit/${eid}`);
      supplyMaterialListApp.orderListModalShowing = true;
      supplyMaterialListApp.orderModalForEdit = true;
      gridOptions.OrderDetailsTitle = "查看采购单";
    }
    /*TODO:编辑事件*/
    const editEvent = (row) => {
      supplyMaterialListApp.editModalShowing = true
      supplyMaterialListApp.currentId = row.eid;
      supplyMaterialListApp.editModalForEdit = true;
      gridOptions.showEditTitle = "编辑";
    }
    /*TODO:子组件触发*/
    const updateOrderId = () => {
      orderId.value = null;
    }
    const closeOrderDetail = (event) => {
      supplyMaterialListApp.orderListModalShowing = event;
    }
    /*TODO:添加到采购单*/
    const addToOrder = (row) => {
      let cart = JSON.parse(localStorage.getItem('cart')) || []
      console.log(cart)
      console.log(row.name)
      if(orderId.value){
        if (row.supplierName != cart[0].supplierName){
          VXETable.modal.message({content:"订单修改状态下只能加入相同供应商的原材料", status: 'info'})
          return
        }
      }
      supplyMaterialListApp.orderModalShowing = true;
      supplyMaterialListApp.currentId = row.eid;
      supplyMaterialListApp.supplierName = row.supplierName;
      supplyMaterialListApp.orderModalForEdit = false;
      gridOptions.OrderDetailsTitle = "添加到采购单";
    }

    /*TODO:查看采购单*/
    const viewOrder = () => {
      // router.push(`/restaurant/material/supplyMaterial/supplyMaterial-edit/${eid}`);
      supplyMaterialListApp.orderListModalShowing = true;
      gridOptions.OrderDetailsTitle = "查看采购单";
    }

    /*TODO:编辑关闭事件*/
    const editEventClose = () => {
      console.log(gridOptions.formData);
      VXETable.modal.message({content: '提交成功', status: 'success'})
    }

    /*TODO:查看事件*/
    const viewEvent = (row) => {
      supplyMaterialListApp.currentId = row.eid;
      supplyMaterialListApp.viewModalShowing = true
      gridOptions.showDetailsTitle = '查看';
    }

    /*TODO:删除事件*/
    const deleteEvent = (row) => {
      SupplyMaterialService.deleteSupplyMaterial(row.eid).then(() => {
        VXETable.modal.message({content: '操作成功', status: 'success'})
      }).catch(error => {
        VXETable.modal.message({content: `系统错误，原因是：${error.message}`, status: 'error'});
      })
    }

    /*TODO:条件查询提交*/
    const reload = () => {
      tablePage.currentPage = 1;
      const $grid = supplyMaterialGrid.value
      $grid.commitProxy('query')//TODO:执行代理方法
    }

    /*TODO:重置搜索*/
    const reset = () => {
      where.value = {}
      const $grid = supplyMaterialGrid.value
      $grid.commitProxy('query')//TODO:执行代理方法
    }

    /*TODO:自定义分页处理*/
    const handlePageChange = ({currentPage, pageSize}) => {
      tablePage.currentPage = currentPage
      tablePage.pageSize = pageSize
      console.log(tablePage)
      const $grid = supplyMaterialGrid.value
      //TODO:执行代理方法
      $grid.commitProxy('query')
    }

    //TODO:这里需要返回才能调用
    return {
      tablePage,
      eid,
      supplyMaterialGrid,
      // editModal,
      gridOptions,
      orderId,
      cart,
      searchExpand,
      viewOrder,
      closeOrderDetail,
      addEvent,
      editEvent,
      viewEvent,
      editEventClose,
      deleteEvent,
      updateOrderId,
      addToOrder,
      viewOrderList,
      where,
      reload,
      reset,
      handlePageChange,
      supplyMaterialListApp,
      ...toRefs(proxyInfo)
    }
  }
})
</script>

<style scoped>
.my-grid66 .alert-message {
  height: 40px;
  display: flex;
  align-items: center;
  margin: 10px 0;
  border-radius: 4px;
  background-color: #e6f7ff;
  border: 1px solid #91d5ff;
}

.my-grid66 .alert-message-icon {
  width: 30px;
  text-align: center;
  color: #409eff;
  margin-right: 8px;
}

.my-grid66 .alert-message-content {
  flex-grow: 1;
  padding-right: 20px;
}

.my-grid66 .page-left {
  position: absolute;
  left: 10px;
  top: 50%;
  transform: translateY(-50%);
  z-index: 10;
}

.my-grid66 .select-count {
  display: inline-block;
  vertical-align: middle;
}

.my-grid66 .my-input {
  width: 100%;
}

.my-grid66 .first-col {
  position: relative;
  height: 20px;
}

.my-grid66 .first-col:before {
  content: "";
  position: absolute;
  left: -15px;
  top: 10px;
  width: 110px;
  height: 1px;
  transform: rotate(28deg);
  background-color: #e8eaec;
}

.my-grid66 .first-col .first-col-top {
  position: absolute;
  right: 4px;
  top: -10px;
}

.my-grid66 .first-col .first-col-bottom {
  position: absolute;
  left: 4px;
  bottom: -10px;
}
</style>
